package com.chixing.service.impl;

import com.chixing.config.DataConfig;
import com.chixing.mapper.ProductMapper;
import com.chixing.pojo.Product;
import com.chixing.service.RecommendService;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.recommender.GenericItemBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.similarity.ItemSimilarity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RecommendServiceImpl implements RecommendService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private DataModel dataModel;
    @Override
    public List<Product> getRecommendProductByProduct(Integer cusId, Integer productId, Integer howMany) {
        List<Product> productList=null;

        try {
             /*
            计算相似度，这里采用皮尔森相似性的相似度
             */
            ItemSimilarity itemSimilarity=new PearsonCorrelationSimilarity(dataModel);
            /*
            构建推荐器，基于物品的协同过滤推荐
             */
            GenericItemBasedRecommender recommender=new GenericItemBasedRecommender(dataModel,itemSimilarity);
            long starTime=System.currentTimeMillis();
            /*
            推荐商品
             */
            List<RecommendedItem> recommendedItemList=recommender.recommendedBecause(cusId,productId,howMany);

            List<Integer> productIds=new ArrayList<>();
            for(RecommendedItem recommendedItem:recommendedItemList){
                System.out.println("recommendedItem"+recommendedItem);
                productIds.add((int) recommendedItem.getItemID());
            }
            System.out.println("推荐出来的商品ids:"+productIds);

            /*
            根据商品id查询商品
             */
            if(productIds!=null&&productIds.size()>0){
                productList=productMapper.selectAllByIds(productIds);
            }else {
                productList=new ArrayList<>();
            }
            System.out.println("推荐数是："+productList.size()+",耗时："+(System.currentTimeMillis()-starTime));

        } catch (TasteException e) {
            e.printStackTrace();
        }

        return productList;
    }
}
